//
//  CoreDataManager.m
//  QuickCare
//
//  Created by lidabiao on 16/7/11.
//  Copyright © 2016年 lidabiao. All rights reserved.
//

#import "CoreDataManager.h"

@implementation CoreDataManager

+(instancetype)shareManager{
    
    static CoreDataManager *manager;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        manager = [[CoreDataManager alloc] init];
        
    });
    
    return manager;

}

-(NSManagedObjectContext *)managedObjectContext{
    
    if (_managedObjectContext == nil) {
        
        _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType: NSMainQueueConcurrencyType];
        
        //设置存储调度器
        [_managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
        
    }
    
    return _managedObjectContext;
    
}

-(NSManagedObjectModel *)managedObjectModel{
    
    if (_managedObjectModel == nil) {
        
        //合并所有的model文件
        _managedObjectModel = [NSManagedObjectModel mergedModelFromBundles: nil];
        
    }
    
    return _managedObjectModel;
    
}

-(NSPersistentStoreCoordinator *)persistentStoreCoordinator{
    
    if (_persistentStoreCoordinator == nil) {
        
        //参数是要保存的managedObjectModel
        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: self.managedObjectModel];
        
        /// 添加存储类型
        /// type：存储类型
        /// configuration：配置信息，一般为nil
        /// URL：数据库保存路径
        ///
        NSURL *url = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];
        
        [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[url URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.db", kFileName]] options:nil error:nil];
        
    }
    
    return _persistentStoreCoordinator;
    
}

-(void)save{
    
    NSError *error = nil;
    
    [self.managedObjectContext save: &error];
    
    if (error == nil) {
        
    }else {
        
        NSLog(@"%@", error.description);
        
    }
    
}

-(NSArray *)executeFetchWithEntityName:(NSString *)entityName format:(NSString *)format
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName: entityName];
    
    request.predicate = [NSPredicate predicateWithFormat: format];
    
    NSError *error = nil;
    
    //执行检索
    NSArray *arr = [kCoreDataManager.managedObjectContext executeFetchRequest:request error: &error];
    
    if (error != nil)
    {
        return nil;
    }
    else
    {
        return arr;
    }
}

@end
